from Tkinter import *
from Canvas import *
import sys
import random

WIDTH  = 400 # width of canvas
HEIGHT = 400 # height of canvas

HPSIZE = 1 # double of point size (must be integer)
COLOR = "#0000FF" # blue

NOPOINTS = 1000

pointList = [] # list of points (used by Canvas.delete(...))

vp = []

def quit(root=None):
    """ quit programm """
    if root==None:
        sys.exit(0)
    root._root().quit()
    root._root().destroy()

def draw():
    """ draw points """
    #for i in range(1,NOPOINTS):
    #    x, y = random.randint(1,WIDTH), random.randint(1,HEIGHT)
    for p in vp:
        x,y = p
        p = can.create_oval(x-HPSIZE, y-HPSIZE, x+HPSIZE, y+HPSIZE,fill=COLOR, outline=COLOR)
        pointList.insert(0,p)

def rotYp():
    """ rotate counterclockwise around y axis """
    global NOPOINTS
    NOPOINTS += 100
    print "In rotYp: ", NOPOINTS 
    can.delete(*pointList)
    draw()

def rotYn():
    """ rotate clockwise around y axis """
    global NOPOINTS
    NOPOINTS -= 100
    print "In rotYn: ", NOPOINTS 
    can.delete(*pointList)
    draw()





    
    
if __name__ == "__main__":
    #check parameters
##    if len(sys.argv) != 2:
##       print "pointViewerTemplate.py"
##       sys.exit(-1)
    f_name = 'cow_points.raw'

    # load points
    points = [map(float, l.split()) for l in file(f_name)]

    # calculate bounding box
    bb = [map(min,zip(*points)), map(max,zip(*points))]
    print bb
    # calculate center of bonding box
    center = [(p[0]+p[1])/2.0 for p in zip(*bb)]
    print center, ' center '
    # calculate scalefactor
    scale = 2.0/ max([(p[1]-p[0]) for p in zip(*bb)])
    
    # translate to zero
    tp =[[p[0]-center[0], p[1]-center[1], p[2]-center[2]] for p in points]

    # scale translated points
    tp =[[p[0]*scale, p[1]*scale, p[2]*scale] for p in tp]

    # transform to viewport
    vp =[[(1.0+p[0])*WIDTH/2, (1.0-p[1])*HEIGHT/2] for p in tp]

    # create main window
    mw = Tk()

    # create and position canvas and buttons
    cFr = Frame(mw, width=WIDTH, height=HEIGHT, relief="sunken", bd=1)
    cFr.pack(side="top")
    can = Canvas(cFr, width=WIDTH, height=HEIGHT)
    can.pack()
    bFr = Frame(mw)
    bFr.pack(side="left")
    bRotYn = Button(bFr, text="<-", command=rotYn)
    bRotYn.pack(side="left")
    bRotYp = Button(bFr, text="->", command=rotYp)
    bRotYp.pack(side="left")
    eFr = Frame(mw)
    eFr.pack(side="right")
    bExit = Button(eFr, text="Quit", command=(lambda root=mw: quit(root)))
    bExit.pack()

    # draw points
    draw()

    # start
    mw.mainloop()
    
